package com.spring.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

@Configuration
@ComponentScan("com.spring")    //自动扫描
@MapperScan("com.spring.dao")
public class Appconfig {
    //用于配置自动扫描的文件和自动注册映射器
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        //要和Spring一起使用MyBatis，需要在spring应用上下文中定义至少两样东西，
        //1. sqlSessionFactory
        //2.数据映射器类  15行已经完成注册映射器
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        return factoryBean.getObject();
    }

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        //下面就是各种配置
        driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("root");
//        jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/express-d?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull");
        return driverManagerDataSource;
    }
}
